package com.example.controller;

import com.example.service.UserService;
import com.example.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 * 演示Controller层的调用关系
 */
@RestController
@RequestMapping("/api/users")
@Api(tags = "用户管理接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    /**
     * 缓存用户信息接口
     * 直接调用UserService.cacheUserInfo -> RedisUtil.set
     */
    @PostMapping("/cache")
    @ApiOperation(value = "缓存用户信息", notes = "将用户信息缓存到Redis中")
    public String cacheUserInfo(@RequestParam String userId, @RequestParam String userInfo) {
        userService.cacheUserInfo(userId, userInfo);
        return "用户信息已缓存";
    }

    /**
     * 更新用户状态接口
     * 调用UserService.updateUserStatus -> UserService.cacheUserInfo -> RedisUtil.set
     */
    @PutMapping("/status")
    @ApiOperation(value = "更新用户状态", notes = "更新用户状态并缓存到Redis")
    public String updateUserStatus(@RequestParam String userId, @RequestParam String status) {
        userService.updateUserStatus(userId, status);
        return "用户状态已更新";
    }

    /**
     * 获取用户信息接口
     * 调用UserService.getUserInfo -> RedisUtil.get
     */
    @GetMapping("/info")
    @ApiOperation(value = "获取用户信息", notes = "从Redis中获取用户信息")
    public String getUserInfo(@RequestParam String userId) {
        return userService.getUserInfo(userId);
    }

    /**
     * 创建订单接口
     * 调用OrderService.createOrder -> RedisUtil.set (直接调用)
     * 同时调用OrderService.createOrder -> UserService.updateUserStatus ->
     * UserService.cacheUserInfo -> RedisUtil.set (间接调用)
     */
    @PostMapping("/orders")
    @ApiOperation(value = "创建用户订单", notes = "为用户创建订单并更新状态")
    public String createOrder(@RequestParam String userId, @RequestParam String orderInfo) {
        String orderId = "order_" + System.currentTimeMillis();
        orderService.createOrder(orderId, orderInfo);
        return "订单创建成功: " + orderId;
    }
}
